package com.study.system.service;

import com.study.system.entity.Admin;
import com.study.system.entity.User;
import com.study.system.exception.UserAccountRecurException;
import com.study.system.exception.UserNotExistException;
import com.study.system.exception.UserVerifyException;
import com.study.system.mapper.UserMapper;
import com.study.system.utils.JWTUtil;
import com.study.system.vo.UserInfoVO;

import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 登录功能Service
     *
     * @param account  账号
     * @param password 密码
     * @return 用户身份验证码Token
     * @throws UserNotExistException 用户不存在异常
     * @throws UserVerifyException   用户密码错误异常
     */
    public String login(String account, String password, String role)
            throws UserNotExistException, UserVerifyException {
        if (role.equals("管理员")) {
            Admin admin = userMapper.findByAccountAdmin(account);
            // 该账号不存在
            if (admin == null || admin.getIsDelete()) {
                throw new UserNotExistException();
            }

            // 用户密码错误
            if (!admin.getPassword().equals(password)) {
                throw new UserVerifyException();
            }
            Map<String, String> map = new HashMap<>();
            map.put("id", admin.getId().toString());
            map.put("username", admin.getName());
            map.put("account", admin.getAccount());
            return JWTUtil.getToken(map);

        } else if (role.equals("用户")) {
            User userDB = userMapper.findByAccount(account);

            // 该账号不存在
            if (userDB == null || userDB.getIsDelete()) {
                throw new UserNotExistException();
            }

            // 用户密码错误
            if (!userDB.getPassword().equals(password)) {
                throw new UserVerifyException();
            }

            Map<String, String> map = new HashMap<>();
            map.put("id", userDB.getId().toString());
            map.put("username", userDB.getUsername());
            map.put("account", userDB.getAccount());
            return JWTUtil.getToken(map);
        }
        return null;
    }

    /**
     * 注册功能Service
     *
     * @param user 用户注册信息
     * @throws UserAccountRecurException 用户已经存在异常
     */
    public Boolean register(User user) throws UserAccountRecurException {
        User userDB = userMapper.findByAccount(user.getAccount());

        // 已经存在用户
        if (userDB != null) {
            throw new UserAccountRecurException();
        }

        return userMapper.insertUser(user) != 0;
    }

    /**
     * 修改用户信息
     *
     * @param user 新的用户信息
     * @return 操作是否成功
     */
    public Boolean modifyUserInfo(User user) {
        if (user.getRole().equals("管理员")) {
            return userMapper.updateAdmin(user) != 0;
        } else {
//            System.out.println(user);
            return userMapper.updateUser(user) != 0;
        }
    }

    public Boolean adminModifyUserInfo(User user) {
        Integer id = user.getId();
        String account = user.getAccount();
        String phone = user.getPhone();
        Integer status = user.getStatus();
        String username = user.getUsername();
        return userMapper.adminUpdateUserInfo(id, account, phone, status, username) != 0;
    }

    /**
     * 删除用户数据
     *
     * @param id 用户id
     * @return 操作是否成功
     */
    public Boolean deleteUser(Integer id) {
        return userMapper.deleteUser(id) != 0;
    }

    /**
     * 查询指定社团的全部成员
     *
     * @param clubId 社团ID
     * @return 查询结果
     */
    public List<UserInfoVO> findClubAllUser(Integer clubId) {
        return userMapper.selectClubAllUser(clubId);
    }

    /**
     * 判断身份信息
     *
     * @param clubId 社团id
     * @param userId 用户id
     * @return 身份判断结果
     */
    public Boolean identifyPost(Integer clubId, Integer userId) {
        Integer result = userMapper.selectUserPost(clubId, userId);
        return result < 4;
    }

    /**
     * 获取用户个人信息
     *
     * @param userId 用户Id
     * @return 用户个人信息
     */
    public UserInfoVO getUserPersonalInfo(Integer userId) {
        return userMapper.getUserInfo(userId);
    }

    /**
     * 修改用户密码
     *
     * @param userId      用户ID
     * @param newPassword 新的用户密码
     * @return 操作是否成功
     */
    public Boolean modifyUserPassword(Integer userId, String newPassword, String role) {
        String oldPassword;

        if (role.equals("管理员")) {
            // 获取原来的密码
            oldPassword = userMapper.getPasswordByUserIdAdmin(userId);
            if (oldPassword.equals(newPassword)) {
                return false;
            }
            userMapper.updatePasswordByUserIdAdmin(userId, newPassword);
        } else {
            // 获取原来的密码
            oldPassword = userMapper.getPasswordByUserId(userId);
            if (oldPassword.equals(newPassword)) {
                return false;
            }
            userMapper.updatePasswordByUserId(userId, newPassword);
        }
        return true;
    }

    // 获取用户职位信息
    public String getUserPostInClub(Integer userId, Integer clubId) {
        return userMapper.getUserPostInClub(userId, clubId);
    }

    public List<User> getAllUserInfo(Integer pageSize, Integer currentIndex) {
        return userMapper.getAllUserInfo(pageSize, currentIndex);
    }

    public Integer getAllUserNumber() {
        return userMapper.getAllUserNumber();
    }

    public Admin getAdminInfo(Integer userId) {
        return userMapper.getAdminInfo(userId);
    }

    public List<UserInfoVO> searchClubMemberByName(Map<String, String> map) {
        // 获取社团id
        Integer clubId = Integer.parseInt(map.get("clubId"));
        String word = map.get("name");
        return userMapper.searchClubMemberByName(word, clubId);
    }

    public Boolean resetPassword(User user) {
        Integer id = user.getId();
        String password = user.getPassword();
        userMapper.updatePasswordByUserId(id, password);
        return true;
    }
}
